package com.qdlc.p2p.dal.dao.impl;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.exception.UpRateException;
import com.qdlc.p2p.common.util.MessageUtil;
import com.qdlc.p2p.dal.common.dao.jpa.BaseDaoImpl;
import com.qdlc.p2p.dal.dao.RateRuleDao;
import com.qdlc.p2p.dal.dto.RateRule;


/**
 * @author wjx
 * @version 2.0
 * @date 2015年4月22日 上午10:32:22
 */
@Repository("rateRuleDao")
public class RateRuleDaoImpl extends BaseDaoImpl<RateRule> implements
		RateRuleDao {

	@Override
	public void updateRateStatus(long id, int isUse) {
		String jpql = "update RateRule set isUse = ?1 where id = ?2";
		Query query = em.createQuery(jpql);
		query.setParameter(1, isUse);
		query.setParameter(2, id);
		int result = query.executeUpdate();
		if (result !=1) {
			throw new UpRateException(MessageUtil.getMessage("MF002002002"));
		}
		
	}

	@Override
	public void updateRateRule(long id, int realPayTotal) {
		String jpql = "update " + Global.DB_PREFIX + "additional_rate_rule set real_pay_total = real_pay_total +?1 where id = ?2";
		Query query = em.createNativeQuery(jpql);
		query.setParameter(1, realPayTotal);
		query.setParameter(2, id);
		int result = query.executeUpdate();
		if (result !=1) {
			throw new UpRateException(MessageUtil.getMessage("MF002002003"));
		}
	}

	@Override
	public int updateRuleStatus(long id, int oldStatus, int nowStatus) {
		String jpql = "UPDATE " + Global.DB_PREFIX + "additional_rate_rule set is_use =?1 where id = ?2 and is_use = ?3";
		Query query = em.createNativeQuery(jpql);
		query.setParameter(1, nowStatus);
		query.setParameter(2, id);
		query.setParameter(3, oldStatus);
		int result = query.executeUpdate();
		return result;
		
	}

	@Override
	public int getRealRepayTotal(long id) {
		String jpql = "select real_pay_total from " + Global.DB_PREFIX + "additional_rate_rule where id = ?1";
		Query query = em.createNativeQuery(jpql);
		query.setParameter(1, id);
		Object obj = query.getSingleResult();
		return Integer.parseInt(obj+"");
	}

	
	
}
